/**
 * Title: PermissionServiceImp.java
 * @author wujin
 * @date 2019年12月30日
 * @version 1.0
 */
package com.pm.service.security.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.pm.entity.po.security.Permission;
import com.pm.mapper.security.PermissionMapper;
import com.pm.service.impl.BaseServiceImpl;
import com.pm.service.security.PermissionService;

/**
 * Title: PermissionServiceImp
 * 
 * @author wujin
 * @date 2019年12月30日
 */
@Service
public class PermissionServiceImpl extends BaseServiceImpl<Permission> implements PermissionService {

	private PermissionMapper permissionMapper;

	@Resource
	public void setBasemapper(PermissionMapper permissionMapper) {
		this.permissionMapper = permissionMapper;
		super.setBaseMapper(permissionMapper);
	}

	@Override
	public List<Permission> getList(Permission permission) {
		List<Permission> result = permissionMapper.getList(permission);
		List<Permission> newResult = new ArrayList<Permission>();
		List<Permission> firstResult = new ArrayList<Permission>();
		if (null != result) {
			if (null != result) {
				for (Permission p : result) {
					if (null == p.getParentId() || p.getParentId() < 1) {
						newResult.add(p);
					} else {
						firstResult.add(p);
					}
				}
			}
			setPermission(newResult, firstResult);
		}
		return newResult;
	}

	private void setPermission(List<Permission> newResult, List<Permission> result) {
		List<Permission> overResult = new ArrayList<Permission>();
		List<Permission> secondResult = new ArrayList<Permission>();
		List<Integer> ids = new ArrayList<Integer>();
		List<Integer> ids2 = new ArrayList<Integer>();
		for (Permission p : newResult) {
			for (Permission m : result) {
				if (p.getPermissionId() == m.getParentId() && !ids2.contains(m.getPermissionId())) {
					ids2.add(m.getPermissionId());
					p.getChildrens().add(m);
					secondResult.add(m);
				} else {
					if (!ids.contains(m.getPermissionId())) {
						ids.add(m.getPermissionId());
						overResult.add(m);
					}
				}
			}
		}
		if (overResult.size() > 0) {
			setPermission(secondResult, overResult);
		}
	}

}
